{% extends 'layout/manage.html' %}
{% load dashboard %}
{% load issues %}
{% block title %}{% endblock %}

{% block css %}
    <style>

        .layui-layer-prompt {
            width: 100px;
            min-width: 46vh;
        }

        .layui-layer-btn0 {
            width: 25%;
            position: relative;
        }

        .layui-layer-btn1 {
            width: 25%;
            position: relative;
        }

        .layui-layer-btn2 {
            width: 25%;
            position: relative;
        }

        .layui-layer-btn3 {
            width: 25%;
            position: relative;
        }

        .layui-layer-btn4 {
            width: 25%;
            position: relative;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 17px;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Rounded sliders */
        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }

        .table-right > tbody > tr > td.label-left {
            width: 90px;
        }

        .table-right > tbody > tr > td {
            border: 0;
        }

        .status-count {
            text-align: center;
            margin-top: 10px;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .status-count .count {
            font-size: 25px;
        }

        .status-count a {
            text-decoration: none;
        }

        .user-item .title {
            margin-bottom: 20px;
        }

        .user-item .avatar, .top-10 .avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .avatar {
              float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .user-item .text {
            line-height: 30px;
        }

        .top-10 .avatar {
            margin-right: 0;
        }

        .top-10 td {
            padding: 5px 10px;
        }

        .top-10 .table > tbody > tr > td {
            border-top: 0;
            border-bottom: 1px solid #ddd;
        }
    </style>

{% endblock %}

{% block content %}
    <div class="container-fluid" style="margin-top: 20px">
        <div class="row">

            <div class="col-md-8">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <i class="fa fa-bar-chart" aria-hidden="true"></i>
                        新增问题趋势
                        <label class="fa! switch">
                            <input type="checkbox" id="mytaskToggle" onclick="mytaskTrigger()">
                            <span class="slider round"></span>
                        </label>
                        只看与我相关
                    </div>
                    <div class="panel-body">
                        <div id="chart" style="width:100%;min-height:200px">

                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <i class="fa fa-quora" aria-hidden="true"></i>
                                问题
                            </div>
                            <div class="panel-body">
                                {% for key,item in status_dict.items %}
                                    <div class="col-sm-4 status-count">
                                        <a href="{% url 'issues' project_id=request.web.project.id %}?status={{ key }}&issues_type={{ type_ids }}">
                                            <div class="count">{{ item.count }}</div>
                                            <div>{{ item.text }}</div>
                                        </a>
                                    </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <i class="fa fa-user" aria-hidden="true"></i>
                                项目成员
                                <span class="col-md-2" style="float: right;"><a
                                        class="layui-btn layui-btn-normal layui-btn-xs"
                                        data-toggle="modal" data-target="#inviteModal">邀请成员</a>
                                </span>

                                {% if request.web.project.creator == request.web.user %}
                                <span class="col-md-2" style="float: right;"><a
                                        class="layui-btn layui-btn-normal layui-btn-xs"
                                        data-toggle="modal" data-target="#memberManage">成员管理</a>
                                      </span>
                                {% endif %}
                            </div>
                            <div class="panel-body user-item">
                                <div class="layui-col-sm12 layui-col-sm-offset1 title">创建者</div>
                                <div class="clearfix" style="margin-bottom: 30px;">
                                    <div class="layui-col-sm3 layui-col-sm-offset1">
                                        <div class="layui-row ws-docs-anim">
                                            {#                                       id {{ request.web.project.creator.id }}#}
                                            <div class="avatar layui-anim" data-anim="layui-anim-rotate">
                                                {% if  request.web.project.creator.git_avatar %}
                                                    <img class="avatar"
                                                         src="{{ request.web.project.creator.git_avatar }}" alt="">
                                                {% else %}
                                                    {{ request.web.project.creator.username.0|upper }}
                                                {% endif %}

                                            </div>
                                        </div>
                                        <div class="text">{{ request.web.project.creator.username }}</div>
                                    </div>
                                </div>
                                <div class="layui-col-sm12 layui-col-sm-offset1 title">参与者</div>
                                <div>
                                    {% for item in join_user %}
                                        <div class="layui-col-sm3 layui-col-sm-offset1">
                                            <div class="layui-row ws-docs-anim">
                                                <div class="avatar layui-anim" data-anim="layui-anim-rotate">
                                                    {% if item.2 %}
                                                        <img class="avatar" src="{{ item.2 }}" alt="">
                                                    {% else %}
                                                        {{ item.1.0 |upper }}
                                                    {% endif %}
                                                </div>
                                            </div>
                                            <div class="text">{{ item.1 }}</div>
                                        </div>
                                    {% endfor %}
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade in" id="inviteModal" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">邀请成员</h4>
                        </div>
                        <div class="modal-body" style="padding-right: 40px;">
                            <form id="inviteForm">
                                {% csrf_token %}
                                {% for item in invite_form %}
                                    <div class="form-group">
                                        <label for="{{ item.id_for_label }}">{{ item.label }}</label>
                                        <span>{% if  item.help_text %}（{{ item.help_text }}）{% endif %}</span>
                                        {{ item }}
                                        <span class="error-msg"></span>
                                    </div>
                                {% endfor %}
                                <button type="button" class="btn btn-success" id="btnGenInviteCode">生成邀请码</button>
                            </form>
                            <div id="inviteArea" class="hide">
                                <hr/>
                                <div class="form-group">
                                    <div class="input-group">
                                        <div class="input-group-btn">
                                            <input type="button" value="邀请链接" class="btn btn-default">
                                        </div>
                                        <input type="text" class="form-control" id="inviteUrl">
                                        <div class="input-group-btn">
                                            <input type="button" value="复制链接" class="btn btn-primary"
                                                   id="btnCopyUrl">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>

            <div class="modal fade in" id="memberManage" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myMembers">成员管理</h4>
                        </div>
                        <div class="modal-body" style="width:300px;padding-right: 40px;word-wrap:break-word;word-break:break-all;display: block;overflow-y: scroll;">
                            <div class="layui-col-sm12 layui-col-sm-offset1 title" ></div>
                        <table id="memberTable"
                               style="word-wrap:break-word;word-break:break-all;min-width:20vh;display: block;overflow-y: scroll;">
                            <tbody>
                           {% for item in join_user %}
                                <tr>
                                    <td style="min-width:300px;">
                                       <div class="layui-col-sm3 layui-col-sm-offset1">
                                        <div class="layui-row ws-docs-anim">
                                            <div class="avatar layui-anim" data-anim="layui-anim-rotate">
                                                {% if item.2 %}
                                                    <img class="avatar" src="{{ item.2 }}" alt="">
                                                {% else %}
                                                    {{ item.1.0 |upper }}
                                                {% endif %}
                                            </div>
                                        </div>
                                        <div class="text">{{ item.1 }}</div>
                                        <div class="text" style="min-width: 220px">加入时间:{{ item.3 }}</div>
                                           <button onclick="removeMember({{ item.0 }})">移除成员</button>
                                           <hr>
                                    </div>
                                    </td>


                                </tr>

                            {% endfor %}
                            </tbody>
                        </table>

                        </div>
                        {% comment %} <div class="modal-body" style="padding-right: 40px;">
                            <form id="inviteForm">
                                {% csrf_token %}
                                {% for item in invite_form %}
                                    <div class="form-group">
                                        <label for="{{ item.id_for_label }}">{{ item.label }}</label>
                                        <span>{% if  item.help_text %}（{{ item.help_text }}）{% endif %}</span>
                                        {{ item }}
                                        <span class="error-msg"></span>
                                    </div>
                                {% endfor %}
                                <button type="button" class="btn btn-success" id="btnGenInviteCode">生成邀请码</button>
                            </form>
                            <div id="inviteArea" class="hide">
                                <hr/>
                                <div class="form-group">
                                    <div class="input-group">
                                        <div class="input-group-btn">
                                            <input type="button" value="邀请链接" class="btn btn-default">
                                        </div>
                                        <input type="text" class="form-control" id="inviteUrl">
                                        <div class="input-group-btn">
                                            <input type="button" value="复制链接" class="btn btn-primary"
                                                   id="btnCopyUrl">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>{% endcomment %}

                    </div>
                </div>
            </div>

            {#        when deadline occur ,show the tip card in dashboard#}
            {#        test btn#}
            {#            <button type="button" class="layui-btn layui-btn-primary" lay-on="test-more-stack">#}
            {#                <span class="layui-badge-dot"></span> 多窗口模式 + 层叠置顶 + Esc 关闭#}
            {#            </button>#}

            <div class="col-md-4">

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <i class="fa fa-cog title-icon"></i>
                        详细
                    </div>
                    <div class="panel-body">
                        <table class="table table-right">
                            <tbody>
                            <tr>
                                <td class="label-left">项目名称 ：</td>
                                <td>{{ request.web.project.name }}-({{ request.web.project.id }})</td>

                            </tr>
                            <tr>
                                <td class="label-left">项目描述 ：</td>
                                <td>{{ request.web.project.desc }}</td>
                            </tr>
                            <tr>
                                <td class="label-left">创建时间 ：</td>
                                <td>{{ request.web.project.create_datetime }}</td>
                            </tr>
                            <tr>
                                <td class="label-left">项目空间 ：</td>
                                <td> {% user_space request.web.project.user_space %}
                                    / {{ request.web.price_policy.project_space }} GB
                                </td>
                            </tr>
                            </tbody>
                        </table>

                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <i class="fa fa-list-ul" aria-hidden="true"></i>
                        动态 {{ top_ten_size }} 次
                    </div>
                    <div class="panel-body top-10">
                        <table class="table"
                               style="word-wrap:break-word;word-break:break-all;height: 300px;min-height: 100vh;display: block;overflow-y: scroll;">
                            <tbody>
                            {% for key,item in top_ten.items %}
                                {#                                                                {{ key }}#}
                                {#                                {{ item }}#}
                                <tr>
                                    <td style="width: 46px;">
                                        {% if item.avatar %}
                                            <img class="avatar" src="{{ item.avatar }}" alt="">
                                        {% else %}
                                            <div class="avatar">{{ item.creator.0|upper }}</div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.type == 1 %}
                                            <div>{{ item.creator }}</div>
                                            <label>
                                                创建了
                                                <a href="{% url 'issues_detail' project_id=request.web.project.id issues_id=item.issue_id %}">{% string_just item.issue_id %}</a>
                                                {#                                            给 {{ item.assign.username }}#}
                                                <label style="text-overflow: ellipsis;">【{{ item.title }}】</label>
                                            </label>
                                            <label style="width: 300px;">
                                                创建于:{{ key }}
                                            </label>
                                        {% endif %}
                                        {% if item.type == 2 %}
                                            <div>{{ item.creator }}</div>
                                            <label>更新了
                                                <a href="{% url 'issues_detail' project_id=request.web.project.id issues_id=item.issue_id %}">{% string_just item.issue_id %}</a>
                                                {#                                            给 {{ item.assign.username }}#}
                                                <label>【{{ item.title }}】</label>
                                                <label>{{ item.desc }}</label>
                                            </label>
                                            <label style="width: 300px;">
                                                更新于:{{ key }}
                                            </label>
                                        {% endif %}
                                        {% if item.type == 3 %}
                                            <div>{{ item.creator }}</div>
                                            <label>回复了 {% if item.reply_to %}{{ item.reply_to }}{% endif %}
                                                <a href="{% url 'issues_detail' project_id=request.web.project.id issues_id=item.issue_id %}">{% string_just item.issue_id %}</a>
                                                {#                                            给 {{ item.assign.username }}#}
                                                <label style="text-overflow: ellipsis;">【{{ item.title }}】</label>
                                                <br>
                                                >> <label style="text-overflow: ellipsis;">{{ item.desc }}</label>
                                            </label>
                                            {#                                            <div>指派#}
                                            {#                                                给 {{ item.assign }}#}
                                            {#                                            </div>#}
                                            <label style="width: 300px;">
                                                回复于:{{ key }}
                                            </label>

                                        {% endif %}

                                    </td>

                                </tr>

                            {% endfor %}
                            </tbody>
                        </table>

                    </div>
                </div>

            </div>
        </div>
    </div>
    {#    <div {% load dashboard %} hidden="hidden"></div>#}
    <input id="echarts_data" value="{{ echarts_data }}" hidden="hidden"/>
    <input id="tasks_count" value="{{ tasks_count }}" hidden="hidden"/>
    <input id="funcs_count" value="{{ funcs_count }}" hidden="hidden"/>
    <input id="bugs_count" value="{{ bugs_count }}" hidden="hidden"/>
    <input id="demand_count" value="{{ demand_count }}" hidden="hidden"/>
    <input id="issues_types" value="{{ issues_types }}" hidden="hidden"/>
    <input id="status_choices" value="{{ status_choices }}" hidden="hidden"/>
    <input id="pid" value="{{ request.web.project.id }}" hidden="hidden"/>
    <input id="type_ids" value="{{ type_ids }}" hidden="hidden"/>
    <input id="all_type_ids" value="{{ all_type_ids }}" hidden="hidden"/>
    <input id="remind_infos" value="{{ remind_infos }}" hidden="hidden"/>
    <input id="username" value="{{ request.web.user.username }}" hidden="hidden"/>
    <input id="project_id" value="{{ request.web.project.id }}" hidden="hidden"/>
    <input id="csrf_token" value="{{ csrf_token }}" hidden="hidden"/>
{% endblock %}

{% block js %}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"
            integrity="sha512-EmNxF3E6bM0Xg1zvmkeYD3HDBeGxtsG92IxFt1myNZhXdCav9MzvuH/zNMBU1DmIPN6njrhX1VTbqdJxQ2wHDg=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript">
        var myChart = echarts.init(document.getElementById("chart"));
        var echartsData = JSON.parse(document.getElementById("echarts_data").value);
        console.log('echartsData', echartsData);
        const yDataNames = ['重新打开', '已关闭', '待反馈', '已忽略', '已解决', '处理中', '新建']
        var tasksCount = JSON.parse(document.getElementById("tasks_count").value);
        console.log('tasksCount', tasksCount);
        if (tasksCount.length == 0) {
            console.log('rray(yDataNames.lengt')
            tasksCount = Array(yDataNames.length).fill(0);
        }
        var funcsCount = JSON.parse(document.getElementById("funcs_count").value);
        if (funcsCount.length == 0) {
            funcsCount = Array(yDataNames.length).fill(0);
        }
        console.log('funcsCount', funcsCount)
        var bugsCount = JSON.parse(document.getElementById("bugs_count").value);
        if (bugsCount.length == 0) {
            bugsCount = Array(yDataNames.length).fill(0);
        }
        var demandCount = JSON.parse(document.getElementById("demand_count").value);
        if (demandCount.length == 0) {
            demandCount = Array(yDataNames.length).fill(0);
        }
        var issues_types = eval(document.getElementById("issues_types"));
        var status_choices = JSON.parse(document.getElementById("status_choices").value);
        var type_ids = document.getElementById("type_ids").value;
        var all_type_ids = document.getElementById("all_type_ids").value;
        var remind_infos = eval(document.getElementById("remind_infos").value);
        console.log('all_type_ids ', all_type_ids);
        console.log('remind_infos ', remind_infos);
        console.log('remind_infos sz ', remind_infos.length);
        if (type_ids) {
            {#if (type_ids.indexOf(",")>-1){#}
            type_ids = type_ids.split(',')
            {% comment %}  }{% endcomment %}
        }
        if (all_type_ids) {
            {#if (type_ids.indexOf(",")>-1){#}
            all_type_ids = all_type_ids.split(',')
            {% comment %}  }{% endcomment %}
        }
        var pid = JSON.parse(document.getElementById("pid").value);

        const dashboardLegendTriggerKey = "mainLegendTrigger" + '{{ request.web.user.id }}' + '_' + '{{ request.web.project.id }}'
        console.log('dashboardLegendTriggerKey', dashboardLegendTriggerKey)

        const mytaskTriggerKey = "mytaskTrigger" + '{{ request.web.user.id }}' + '_' + '{{ request.web.project.id }}'
        console.log('mytaskTriggerKey', mytaskTriggerKey)

        var username = document.getElementById("username").value;
        var project_id = eval(document.getElementById("project_id").value);


        // 基于准备好的dom，初始化echarts实例
        myChart.showLoading();


        option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    // Use axis to trigger tooltip
                    type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
                }
            },
            legend: {},
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                triggerEvent: true,
            },
            yAxis: {
                type: 'category',
                data: yDataNames,
                triggerEvent: true,
            },
            series: [
                {
                    name: '任务',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: tasksCount
                },
                {
                    name: '功能',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: funcsCount
                },
                {
                    name: 'Bug',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: bugsCount
                },
                {
                    name: '需求确认',
                    type: 'bar',
                    stack: 'total',
                    label: {
                        show: true
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: demandCount
                },

            ]
        };
        let yMatchTypes = ["新建", "处理中", "已解决", "已忽略", "待反馈", "已关闭", "重新打开"]
        let xMatchTypes = ["任务", "功能", "Bug", "需求确认"]

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        myChart.hideLoading();
        myChart.on("click", function (e) {
            console.log(e.name)
            console.log(e.seriesName)
            console.log(e.seriesName == 'Bug')
            {#alert('chart on click>>', params);#}
            {#console.log((yMatchTypes.indexOf(e.name) + 1))#}
            {#console.log((all_type_ids[(xMatchTypes.indexOf(e.seriesName))]))#}
            if (e.name && e.seriesName) {
                {#alert('issues_types', (xMatchTypes.indexOf(e.seriesName)))#}
                window.location.href = "/manage/" + pid + "/issues/?status=" + (yMatchTypes.indexOf(e.name) + 1) +
                    "&issues_type=" + (all_type_ids[(xMatchTypes.indexOf(e.seriesName))])
            }
        })


        function legendTriggerRefresh() {
            let legend = localStorage.getItem(dashboardLegendTriggerKey);
            console.log('mainLegendTrigger le>>', legend);
            let legendArr = ['任务', '功能', 'Bug', '需求确认']
            if (!legend) {
                legend = '任务,功能,Bug,需求确认'
                localStorage.setItem(dashboardLegendTriggerKey, legend);
            } else {
                if (legend) {
                    let splitLegend = legend.split(",");
                    for (var i = 0; i < 4; i++) {
                        myChart.setOption({
                            legend: {selected: {[legendArr[i]]: false}},
                        })
                    }
                    for (s in splitLegend) {
                        if (splitLegend[s] == '任务') {
                            myChart.setOption({
                                legend: {selected: {['任务']: true}}
                            })
                        } else if (splitLegend[s] == '功能') {
                            myChart.setOption({
                                legend: {selected: {['功能']: true}}
                            })
                        } else if (splitLegend[s] == 'Bug') {
                            myChart.setOption({
                                legend: {selected: {['Bug']: true}}
                            })
                        } else if (splitLegend[s] == '需求确认') {
                            myChart.setOption({
                                legend: {selected: {['需求确认']: true}}
                            })
                        }
                    }

                } else {
                    console.log('mainLegendTrigger', legend)
                    {% comment %}for (var i = 0; i < 5; i++) {
                        myChart.setOption({
                            legend: {selected: {[legendArr[i]]: false}},
                        })
                    }{% endcomment %}
                }
            }
        }

        myChart.on('legendselectchanged', function (e) {
            if (e.selected[e.name]) {
                // 点击项是选中状态
                console.log(e.name + ' checked')
                sendFreshMainEchartLegendTriggerVal(e.selected)
            } else {
                // 点击项是取消状态
                console.log(e.name + ' un checked')
                sendFreshMainEchartLegendTriggerVal(e.selected)
            }
            // do something
        });


        function sendFreshMainEchartLegendTriggerVal(val) {
            let reqVal = ''
            if (val.任务) {
                if (reqVal.length > 0) {
                    reqVal += ','
                }
                reqVal += '任务'
            }
            if (val.功能) {
                if (reqVal.length > 0) {
                    reqVal += ','
                }
                reqVal += '功能'
            }
            if (val.Bug) {
                if (reqVal.length > 0) {
                    reqVal += ','
                }
                reqVal += 'Bug'
            }
            if (val.需求确认) {
                if (reqVal.length > 0) {
                    reqVal += ','
                }
                reqVal += '需求确认'
            }
            console.log(reqVal)
            if (!reqVal) {
                alert('至少保留一项😄')
                location.reload();
                return
            }
            $.ajax({
                url: "{% url 'main_echart_legend_cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": reqVal,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.code) {
                        localStorage.setItem(dashboardLegendTriggerKey, reqVal)
                        console.log("reload")
                        {#legendTriggerRefresh()#}
                        {#reloadWorkBenchJson()#}
                        location.reload();
                        {#$("#tasklist").load(issues_object_list=[])#}
                    } else {

                    }
                }

            })
        }

        //deprecated
        function sendInitDashboardEchartLegendTriggerVal() {
            const initialDashBoardLegend = '任务,功能,Bug,需求确认'
            $.ajax({
                url: "{% url 'main_echart_legend_cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": initialDashBoardLegend,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.code) {
                        localStorage.setItem(dashboardLegendTriggerKey, initialDashBoardLegend)
                        console.log("sendInitDashboardEchartLegendTriggerVal reload")
                        {#legendTriggerRefresh()#}
                        {#reloadWorkBenchJson()#}
                        location.reload();
                        {#$("#tasklist").load(issues_object_list=[])#}
                    } else {

                    }
                }

            })
        }

        function mytaskTrigger() {
            console.log("mytaskTrigger")
            let isChecked = $('input[type="checkbox"]').prop('checked');
            if (isChecked) {
                console.log("勾选");
                localStorage.setItem(mytaskTriggerKey, "on")
            } else {
                console.log("未勾选");
                localStorage.setItem(mytaskTriggerKey, "off")
            }
            sendFreshTriggerVal()

        }

        function storageTriggerInit() {
            let item = localStorage.getItem(mytaskTriggerKey);
            if (!item) {
                item = 'off'
                localStorage.setItem(mytaskTriggerKey, item);
            } else {
                console.log("mytaskTrigger", item)
                if (item == "on") {
                    $('input[type="checkbox"]').prop('checked', true);
                } else {
                    $('input[type="checkbox"]').prop('checked', false);
                }
            }
            legendTriggerRefresh()
        }

        storageTriggerInit()

        $(function () {
            bindCopyUrl();
        });

        /**
         * 点击拷贝链接url
         * */
        function bindCopyUrl() {
            $('#btnCopyUrl').click(function () {
                var textInput = $('#inviteUrl')[0]; // document.getElementById('inviteUrl')
                textInput.select();

                document.execCommand("Copy");
                layui.use(function () {
                    var layer = layui.layer;
                    // Welcome
                    layer.msg('复制成功', {icon: 6});
                });
            })
        }

        function sendFreshTriggerVal() {
            {#const  pid = {{ request.web.project.id }})#}
            $.ajax({
                url: "{% url 'cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": localStorage.getItem(mytaskTriggerKey),
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.code) {
                        console.log("reload")
                        location.reload();
                    } else {

                    }
                }

            })
        }

        function showMemberWithProjInfos() {
            alert("暂无")
        }

        var INVITE_URL = "{% url 'invite_url' project_id=request.web.project.id %}";

        $(function () {
            bindCreateInviteCode();
        });

        /**
         *       点击生成邀请链接
         */
        function bindCreateInviteCode() {
            $('#btnGenInviteCode').click(function () {
                $('.error-msg').empty();
                $.ajax({
                    url: INVITE_URL,
                    type: "POST",
                    data: $('#inviteForm').serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            $('#inviteArea').removeClass('hide').find('#inviteUrl').val(res.data);
                        } else {
                            $.each(res.error, function (k, v) {
                                $('#id_' + k).next('.error-msg').text(v[0]);
                            })
                        }
                    }
                })
            })
        }


        layui.use(function () {
            var $ = layui.$;

            //演示动画
            $('.ws-docs-anim .layui-anim').on('mouseover', function () {
                var othis = $(this), anim = othis.data('anim');

                //停止循环
                if (othis.hasClass('layui-anim-loop')) {
                    return othis.removeClass(anim);
                }

                othis.removeClass(anim);

                setTimeout(function () {
                    othis.addClass(anim);
                });
                //恢复渐隐
                if (anim === 'layui-anim-fadeout') {
                    setTimeout(function () {
                        othis.removeClass(anim);
                    }, 1300);
                }
            });
        });

        layui.use(function () {
            var layer = layui.layer;
            var util = layui.util;
            var form = layui.form;
            var $ = layui.$;
            if (remind_infos.length > 0) {
                let is_link = false
                for (i in remind_infos) {
                    let showCloseAllBtn = true
                    if (remind_infos.length == 1) {
                        console.log('length 1')
                        showCloseAllBtn = false
                    }
                    let ri = remind_infos[i]
                    let btn = []
                    let btn0Name = '查看详情'
                    let btn1Name = '回复消息'
                    let btn2Name = '本次关闭'
                    let btn3Name = '全部关闭'
                    let btn4Name = '不再提醒'
                    btn.push(btn0Name)
                    btn.push(btn1Name)
                    btn.push(btn2Name)
                    if (showCloseAllBtn) {
                        btn.push(btn3Name)
                        btn.push(btn4Name)
                    } else {
                        btn.push(btn4Name)
                    }
                    if (ri.link.length > 0) {
                        is_link = true
                    } else {
                    }
                    // 事件
                    //when dashboard receive the deadline news , trigger this deadline card instantly
                    var that = this;
                    // 多窗口模式 + 层叠置顶 + Esc 关闭
                    layer.open({
                        type: 1,
                        title: ri.type == 1 ? '系统信息 (按ESC键可关闭)' : ri.type == 2 ? '提醒信息 (按ESC键可关闭)' : '',
                        area: ['390px', '260px'],
                        shade: 0,
                        maxmin: true,
                        offset: [ // 为了便于演示，此处采用随机坐标
                            Math.random() * ($(window).height() - 300),
                            1 * $(window).width() - 400
                        ],
                        content: '<div style="padding: 16px;">' +
                            '<label style="color: deeppink">' + ri.content + '</label>' +
                            '</div>',
                        btn: btn,
                        yes: function () {
                            {#$(that).click();#}
                            if (is_link) {
                                window.open(ri.link)
                                //set the msg already readed through ajax
                            } else {
                                //todo reply hint msg
                            }
                        },
                        {% comment %} btn1: function () {
                             layer.msg('btn1 ', {icon: 1});
                         },{% endcomment %}
                        btn2: function () {
                            console.log('click btn2  ', btn[1])
                            console.log(ri.content);
                            console.log(ri.sender);
                            // 事件
                            layer.prompt({
                                title: '回复来自 ' + ri.sender + ' 的消息:', formType: 2, btn: ['回复了', '取消了'],
                                placeholder: ri.content
                            }, function (value, index, elem) {
                                console.log('elem', elem);
                                console.log('value', value);
                                console.log('index', index);
                                {#let replyPromptLayer = document.getElementById('layui-layer'+index)#}
                                if (value === '') return elem.focus();
                                layer.msg('获得：' + util.escape(value)); // 显示 value
                                sendReplyMsg(ri.sender, util.escape(value))
                                // 关闭 prompt
                                layer.close(index);
                            });
                        },
                        btn3: function () {
                            layer.close();
                            console.log('click btn3  ', btn[2])
                            layer.msg('再次查看可从提醒处查看', {icon: 7})
                        },
                        btn4: function () {
                            if (showCloseAllBtn) {
                                layer.closeAll();
                                console.log('click btn4  ', btn[3])
                                layer.msg('再次查看可从提醒处查看', {icon: 7})
                            } else {
                                console.log('click btn4 ', btn[4])
                                status(ri.id)
                                layer.msg('已将状态更改到已读', {icon: 1})
                            }
                        },
                        btn5: function () {
                            console.log('click btn4 ', btn[4])
                            status(ri.id)
                            layer.msg('已将状态更改到已读', {icon: 1})
                        },
                        zIndex: layer.zIndex, // 重点 1 --- 初始设置当前最高层叠顺序，
                        success: function (layero, index) {
                            layer.setTop(layero); // 重点 2 --- 保持选中窗口置顶

                            // 记录索引，以便按 esc 键关闭。事件见代码最末尾处。
                            layer.escIndex = layer.escIndex || [];
                            layer.escIndex.unshift(index);
                            // 选中当前层时，将当前层索引放置在首位
                            layero.on('mousedown', function () {
                                var _index = layer.escIndex.indexOf(index);
                                if (_index !== -1) {
                                    layer.escIndex.splice(_index, 1); //删除原有索引
                                }
                                layer.escIndex.unshift(index); //将索引插入到数组首位
                            });
                        },
                        end: function () {
                            //更新索引
                            if (typeof layer.escIndex === 'object') {
                                layer.escIndex.splice(0, 1);
                            }
                        }
                    });
                }
            }
            // 多窗口模式 - esc 键
            $(document).on('keyup', function (e) {
                if (e.keyCode === 27) {
                    layer.close(layer.escIndex ? layer.escIndex[0] : 0);
                }
            });
        });

        function sendReplyMsg(receiver, message) {
            $.ajax({
                url: "{% url 'send_private_hint_msg' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "receiver": receiver,
                    "message": message,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        layer.msg('发送成功', {icon: 6})

                        {#location.reload();#}
                        {#$("#badge").load(location.href + " #badge")#}
                    } else {
                        layer.msg('发送异常', {icon: 5})
                    }
                }
            })
        }

        function status(key) {
            $.ajax({
                url: "{% url 'remind_status' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "id": key,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        location.reload();
                        {#$("#badge").load(location.href + " #badge")#}
                    } else {
                    }
                }
            })
        }


        layui.use(function () {
            var layer = layui.layer;
            var util = layui.util;
            // 事件
            util.on('lay-on', {
                'test-tips-prompt-2': function () {
                    layer.prompt({title: '请输入文本', formType: 2}, function (value, index, elem) {
                        if (value === '') return elem.focus();
                        layer.msg('获得：' + util.escape(value)); // 显示 value
                        const position = 'dashboard';
                        // 关闭 prompt
                        var wsUrl = 'ws://' + window.location.host + '/chat/ws/' + project_id + '/' + user_id + '/' + username
                        if (!ws) {
                            ws = new WebSocket(wsUrl);
                            console.log(ws);
                        } else {
                        }
                        layer.close(index);
                    });
                },

            })
        });

        let atTaskFlag = false

        function triggerReply(replyMsg, replyTo) {
            const atMemberFlag = true
            var message = replyMsg
            if (!message) {
                console.log('message can not be empty')
                return
            }
            console.log('message', message)
            if (message.startsWith('http')) {
                console.log('transfer to _blank a')
                message = "<a href=" + message + " target='_blank'" + ">" + message + "</a>"
            }
            let stringifyMsg = JSON.stringify({
                'message': message,
                'type': 'normal'
            });
            let atMembersConfirm = [replyTo]
            if (atMemberFlag) {
                console.log('atMemberFlag', atMemberFlag)
                if (atMembersConfirm.length > 0 && !atTaskFlag) {
                    //send hint msg
                    stringifyMsg = JSON.stringify({
                        'message': message,
                        'type': 'hint',
                        'receivers': atMembersConfirm,
                        'sender': '{{ request.web.user.username }}'
                    });
                }
            }

            if (atTaskFlag) {
                console.log('atTaskFlag', atTaskFlag)
                let atTasksConfirm = []
                for (t in atTaskIds) {
                    if (message.indexOf('#' + atTaskIds[t]) > -1) {
                        console.log('confirm hint task ', atTaskIds[t])
                        atTasksConfirm.push(atTaskIds[t])
                    }
                }
                if (atTasksConfirm.length > 0) {
                    let task_message = ''
                    for (t in atTasksConfirm) {
                        let taskid = atTasksConfirm[t]
                        const request_detail_url = "{% url 'issues_detail' project_id=request.web.project.id issues_id=1 %}".replace("detail/1", "detail/" + taskid)
                        task_message = "<a href=" + request_detail_url + " target='_blank'>" + message + "</a>"
                        break;
                    }
                    //send hint msg
                    stringifyMsg = JSON.stringify({
                        'message': task_message,
                        'type': atMemberFlag ? 'hint' : 'normal',
                        'receivers': atMemberFlag ? atMembersConfirm : [],
                        'sender': '{{ request.web.user.username }}'
                    });
                }
            }

            console.log(stringifyMsg)

            if (isOnlineCurrUser()) {
                let send = ws.send(stringifyMsg);
                console.log('send', send)
                atMemberNames = []
                atTaskIds = []
                atTaskFlag = false
            } else {
                console.log('reconnect ws...')
                createOrConnectWebSocket()
                var count = 0
                while (!isOnlineCurrUser() && count < 100) {
                    count++
                    {#createOrConnectWebSocket()#}
                    console.log('reconnect ws 3')
                }
                console.log('ws.send(stringifyMsg)', stringifyMsg)
                let send = ws.send(stringifyMsg);
                console.log('send', send)
                messageInputDom.value = '';
                atMemberNames = []
                atTaskIds = []
                atTaskFlag = false
            }
        }


        function chatReplySetup() {
            {#websocketInit()#}
            {#$("#chatMembers").html($("#user_list").val())#}
            {#websocketInit()#}
            document.querySelector('.layui-layer-input').focus();
            document.querySelector('.layui-layer-input').onkeyup = function (e) {
                if (e.keyCode === 13) {  // enter, return
                    document.querySelector('.layui-layer-btn0').click();
                }
            };

            document.querySelector('.layui-layer-input').change = function (e) {
                console.log('msg input change:', e)
            }
            document.querySelector('.layui-layer-btn0').onclick = function (e) {
                var messageInputDom = document.querySelector('.layui-layer-input');
                console.log('reply msg: ', messageInputDom)
                var message = messageInputDom.value;
                if (!message) {
                    console.log('message can not be empty')
                    return
                }
                console.log('message', message)
                if (message.startsWith('http')) {
                    console.log('transfer to _blank a')
                    message = "<a href=" + message + " target='_blank'" + ">" + message + "</a>"
                }
                let stringifyMsg = JSON.stringify({
                    'message': message,
                    'type': 'normal'
                });
                let atMembersConfirm = []
                if (atMemberFlag) {
                    console.log('atMemberFlag', atMemberFlag)
                    for (m in atMemberNames) {
                        if (message.indexOf('@' + atMemberNames[m]) > -1) {
                            console.log('confirm hint user ', atMemberNames[m])
                            atMembersConfirm.push(atMemberNames[m])
                        }
                    }
                    if (atMembersConfirm.length > 0 && !atTaskFlag) {
                        //send hint msg
                        stringifyMsg = JSON.stringify({
                            'message': message,
                            'type': 'hint',
                            'receivers': atMembersConfirm,
                            'sender': '{{ request.web.user.username }}'
                        });
                    }
                }

                if (atTaskFlag) {
                    console.log('atTaskFlag', atTaskFlag)
                    let atTasksConfirm = []
                    for (t in atTaskIds) {
                        if (message.indexOf('#' + atTaskIds[t]) > -1) {
                            console.log('confirm hint task ', atTaskIds[t])
                            atTasksConfirm.push(atTaskIds[t])
                        }
                    }
                    if (atTasksConfirm.length > 0) {
                        let task_message = ''
                        for (t in atTasksConfirm) {
                            let taskid = atTasksConfirm[t]
                            const request_detail_url = "{% url 'issues_detail' project_id=request.web.project.id issues_id=1 %}".replace("detail/1", "detail/" + taskid)
                            task_message = "<a href=" + request_detail_url + " target='_blank'>" + message + "</a>"
                            break;
                        }
                        //send hint msg
                        stringifyMsg = JSON.stringify({
                            'message': task_message,
                            'type': atMemberFlag ? 'hint' : 'normal',
                            'receivers': atMemberFlag ? atMembersConfirm : [],
                            'sender': '{{ request.web.user.username }}'
                        });
                    }
                }

                console.log(stringifyMsg)

                if (isOnlineCurrUser()) {
                    let send = ws.send(stringifyMsg);
                    console.log('send', send)
                    messageInputDom.value = '';
                    atMemberNames = []
                    atTaskIds = []
                    atMemberFlag = false
                    atTaskFlag = false

                } else {
                    console.log('reconnect ws...')
                    createOrConnectWebSocket()
                    var count = 0
                    while (!isOnlineCurrUser() && count < 100) {
                        count++
                        {#createOrConnectWebSocket()#}
                        console.log('reconnect ws 3')
                    }
                    console.log('ws.send(stringifyMsg)', stringifyMsg)
                    let send = ws.send(stringifyMsg);
                    console.log('send', send)
                    messageInputDom.value = '';
                    atMemberNames = []
                    atTaskIds = []
                    atMemberFlag = false
                    atTaskFlag = false
                }
            };


            {% comment %}function chatHisInit() {

                let mychatLog = localStorage.getItem('mychatLog' + project_id)
                {#console.log('mychatLog>>',mychatLog);#}
                if (mychatLog && mychatLog != 'undefined') {
                    document.querySelector('#chat-log').innerHTML += (mychatLog);
                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                }
            }{% endcomment %}

            {#chatHisInit()#}
        }


        function websocketInit() {
            ws.onmessage = function (e) {
                console.log('evt e ', e)
                var data = JSON.parse(e.data);

                console.log('>>>>>', data.type)
                if (data.type == 'userlist.message') {
                    let userlistval = eval(data.message);
                    console.log(userlistval)
                    userlist_online = userlistval
                    console.log('userlistmessage refresh userlist ')
                    var userlist = ''
                    for (let i = 0; i < userlistval.length; i++) {
                        userlist += ` <li>` + userlistval[i] + `</li>`;
                    }
                    $("#user_list").val(userlist)
                    $("#chatMembers").html(userlist);
                    return
                } else if (data.type == 'private.message') {
                    var message = data['message'];
                    document.querySelector('#chat-log').innerHTML += ('<label style="color: hotpink">' + message + '</label>' + '<br>');
                    localStorage.setItem('mychatLog' + project_id, document.querySelector('#chat-log').innerHTML)
                    const notify_audio = document.getElementById('notifyAudio')
                    notify_audio.play();

                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                    $("#badge").load(location.href + " #badge")

                } else {
                    var message = data['message'];
                    document.querySelector('#chat-log').innerHTML += (message + '<br>');
                    localStorage.setItem('mychatLog' + project_id, document.querySelector('#chat-log').innerHTML)
                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                }


                {#var message = eval('(' + e.data + ')');#}
                {#switch (message.type) {#}
                {#case#}
                {#'init'#}
                {#:#}
                {#changeNoReadLogs();#}
                {#var bind = '{"type":"bind","from_id":"' + from_id + '","to_id":"' + to_id + '"}';#}
                {#ws.send(bind);#}
                {#message_load();#}
                {#    break;#}

                {% comment %}}{% endcomment %}
            };
            ws.onclose = function (e) {
                console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
            };

        }

        function getValue(obj, str, type) {
            console.log('getvalue')
            var input = window.document.getElementById(obj);
            input.value += str + ' ';
            if (type === 'member') {
                if (atMemberNames.indexOf(str) > -1) {
                    console.log('user indexof has')
                } else {
                    atMemberNames.push(str)
                }
                if (atMemberNames.length > 0) {
                    atMemberFlag = true
                }
                console.log(atMemberNames)
            } else if (type === 'task') {
                taskid = parseInt(str.split(',')[0])
                if (all_object_ids.includes(taskid) && atTaskIds.includes(taskid)) {
                    console.log('task contains')
                } else if (all_object_ids.includes(taskid) && !atTaskIds.includes(taskid)) {
                    atTaskIds.push(taskid)
                }
                if (atTaskIds.length > 0) {
                    atTaskFlag = true
                }
                console.log(atTaskIds)
            }
            document.querySelector('#chat-message-input').focus();
        }

        function isOpen(ws) {
            return ws.readyState === ws.OPEN
        }


        var interval_timer = null;//计时器
        var timer_count = 0;

        var ws;

        function createOrConnectWebSocket() {
            var wsUrl = 'ws://' + window.location.host + '/chat/ws/' + project_id + '/' + user_id + '/' + username
            var count = 0
            if (!ws) {
                ws = new WebSocket(wsUrl);
                websocketInit();
            } else {
                if (!isOnlineCurrUser() && count < 100) {
                    count++
                    ws = null;
                    createOrConnectWebSocket();
                }
            }
            // 开启定时器
            init_start_timer();
        }

        function removeMember(remove_user_id) {
            $.ajax({
                url: "{% url 'remove_user_from_project' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "remove_user_id": remove_user_id,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        layer.msg('移除了成员')
                        {#location.reload();#}
                        $("#memberTable").load(location.href + " #memberTable")
                    } else {
                    }
                }
            })
        }

    </script>

{% endblock %}